package com.itlong.cloud.commons.service.impl;

import com.itlong.cloud.POJO.DTO.app.AppUserAccountBalanceDTO;
import com.itlong.cloud.POJO.PO.AppUserAccountBalancePO;
import com.itlong.cloud.POJO.PO.AppUserBalanceChangeRecordPO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.commons.dao.IAccountBalanceDao;
import com.itlong.cloud.commons.service.IAccountBalanceService;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.PayTypeEnum;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.data.handler.SqlUtil;
import com.itlong.cloud.utils.random.RandomUtil;
import com.itlong.cloud.commons.dao.IBalanceChangeRecordDao;
import com.itlong.cloud.commons.dao.IPaymentTradeDao;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <desc>
 * 账户余额及扣费暴露接口
 * </desc>
 *
 * @createDate 2018/4/23
 */
@Service
@RefreshScope
public class AccountBalanceServiceImpl implements IAccountBalanceService {

    @Autowired
    private IAccountBalanceDao iAccountBalanceDao;

    @Autowired
    private IBalanceChangeRecordDao iBalanceChangeRecordDao;

    @Autowired
    private IPaymentTradeDao iPaymentTradeDao;
    @Value("${" + PlatformConstants.APP_USER_TOKEN_KEY + "}")
    public String APP_USER_TOKEN_KEY;

    /**
     * <desc>
     *      根据userId查询余额
     * <desc/>
     * @param  userId   带查询的userId
     * @return 余额
     * @author Juguang.S
     * @createDate 2018/4/24
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public BigDecimal getBalanceByUserId(String userId) {
        BigDecimal accountMoney = BigDecimal.ZERO;
        if (StringUtils.isEmpty(userId)) {
            return accountMoney;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        AppUserAccountBalancePO appUserAccountBalance = iAccountBalanceDao.getBalanceByParams(params);
        if (appUserAccountBalance != null) {
            accountMoney = appUserAccountBalance.getAccountMoney();
        }
        return accountMoney;
    }


    /**
     * <desc>
     *      扣费
     * <desc/>
     * @param
     * @return
     * @author Juguang.S
     * @createDate 2018/4/24
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Map<String, Object> updateBalance(AppUserAccountBalanceDTO appUserAccountBalanceDTO) {
        try {

            String faceId = appUserAccountBalanceDTO.getFaceId();
            String cardId = appUserAccountBalanceDTO.getCardId();
            BigDecimal accountMoney = new BigDecimal(appUserAccountBalanceDTO.getNum());

            Map<String, Object> returnMap = new HashMap<>();

            Map<String, Object> params = new HashMap<>();
            //保存用户余额变动记录表
            AppUserBalanceChangeRecordPO recordPO = new AppUserBalanceChangeRecordPO();
            recordPO.setMoney(accountMoney);
            recordPO.setRecordId(RandomUtil.getRandomStringByLength(32));
            recordPO.setRecordType(2);
            recordPO.setStatus(DataStatusEnum.NORMAL.getType());
            recordPO.setCreateTime(new Date());

            //人脸识别扣费
            if(PayTypeEnum.FACE_PAY.getType() == appUserAccountBalanceDTO.getPayType() && faceId !=null){
//                params.put("faceId", faceId);
                //先从数据库根据faceId查询出相对应的userId
                String faceUserId = iAccountBalanceDao.getUserId(faceId);
                if(StringUtils.isNotEmpty(faceUserId)){
                    recordPO.setUserId(faceUserId);
                }else{
                    returnMap.put("status", 2);
                    return returnMap;
                }
                recordPO.setRecordSource(PayTypeEnum.FACE_PAY.getType());
                //status 0代表成功 1代表余额不足 2代表Userid的账号余额不存在
//                AppUserAccountBalancePO faceShowPO = iAccountBalanceDao.getBalanceByParams(params);
                /*if (faceShowPO == null) {
                    returnMap.put("status", 2);
                    return returnMap;
                }*/
                params.put("faceId", faceId);
                params.put("updateTime",new Date());
                params.put("num",accountMoney);
                Integer updateData = iAccountBalanceDao.updateByFaceId(params);
                //余额不足
                if(updateData == 0){
                    returnMap.put("status", 1);
                    return returnMap;
                }
            }
            //电梯刷卡扣费
            if(PayTypeEnum.ELEVATOR_CARD_PAY.getType() == appUserAccountBalanceDTO.getPayType() && StringUtils.isNotEmpty(cardId)){
                String cardUserId = iAccountBalanceDao.getCardUserId(cardId);
                if(cardUserId == null){
                    return null;
                }
                params.put("userId", cardUserId);
                recordPO.setUserId(cardUserId);
                recordPO.setRecordSource(PayTypeEnum.ELEVATOR_CARD_PAY.getType());
                params.put("updateTime",new Date());
                params.put("num",accountMoney);
                Integer updateData = iAccountBalanceDao.updateByUserId(params);
                //余额不足
                if(updateData == 0){
                    returnMap.put("status", 1);
                    return returnMap;
                }
            }

            returnMap.put("status", 0);
            returnMap.put("recordId", recordPO.getRecordId());

            iBalanceChangeRecordDao.save(SqlUtil.durableData(recordPO, PlatformConstants.TABLE_SAVE));

            return returnMap;
        } catch (Exception e) {
            throw new DataAccessException("【演示版WeChatPayServiceImpl】_updateBalance更新账户余额失败", e);
        }
    }

    /**
     * <desc>
     *      根据userId查询对象
     * <desc/>
     * @param  userId   带查询的userId
     * @return 余额
     * @author Juguang.S
     * @createDate 2018/4/24
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public AppUserAccountBalancePO getUser(String userId) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        AppUserAccountBalancePO appUserAccountBalance = iAccountBalanceDao.getBalanceByParams(params);
        return appUserAccountBalance;
    }


    /**
     * <desc>
     *      检查当前订单状态是否为支付成功
     * </desc>
     *
     * @param billsId 账单id
     * @return
     * @author Jiaqi.X
     * @createDate 2018/04/27
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Boolean checkTradeSuccess(String billsId,String userId,String tradeId) {

        return iPaymentTradeDao.checkTradeSuccess(billsId,userId,tradeId) > 0;
    }

    /**
     * <desc>
     *      更新余额流水来源id
     * </desc>
     *
     * @param recordId 订单id
     * @param sourceId  来源id
     * @return
     * @author Jiaqi.X
     * @createDate 2018/04/28
     */
    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public Integer updateTradeSourceId(String recordId,String sourceId){
        return iAccountBalanceDao.updateTradeSourceId(recordId,sourceId);
    }

    /**
     * <desc>
     *      根据账单ID查询月卡订单的截止时间
     * </desc>
     *
     * @param billId 订单id
     * @return
     * @author Juguang.S
     * @createDate 2018/11/12
     */
    @Override
    public String getMonthCardTime(String billId) {
        return iAccountBalanceDao.getMonthCardTime(billId);
    }
}